package ru.spb.osll.myfit.server.parser;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import org.apache.log4j.Logger;
import ru.spb.osll.myfit.common.Suite;
import ru.spb.osll.myfit.server.Configurator;

import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

import static ru.spb.osll.myfit.server.SuiteUtils.getSuitePathFromId;
import static ru.spb.osll.myfit.server.parser.PageUtils.getFullPath;

public class SuiteHandler {
  private Configurator m_configurator = Configurator.getInstance();
  private static Logger m_logger = Logger.getLogger(SuiteHandler.class);

  public void saveSuite(Suite suite) {
    try {
      String suitesDirectory = m_configurator.getSuitesDir();

      String suiteDirectoryPath = getFullPath(suitesDirectory, suite.getId());

      File suiteDirectory = new File(suiteDirectoryPath);

      if (!suiteDirectory.exists()) {
        suiteDirectory.mkdirs();
      }

      String suiteFilePath = getSuitePathFromId(suite.getId());

      FileWriter fileWriter = new FileWriter(suiteFilePath);
      BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

      XStream xStream = new XStream();
      xStream.processAnnotations(Suite.class);

      bufferedWriter.write(xStream.toXML(suite));

      bufferedWriter.close();
    } catch (IOException e) {
      m_logger.error("Could not write suite file with id " + suite.getId());
    }
  }

  public Suite getSuite(String path) throws FileNotFoundException, ParserConfigurationException {
    Suite suite;
    XStream xStream = new XStream();
    xStream.processAnnotations(Suite.class);

    File suiteFile = new File(path);
    if (suiteFile.exists()) {
      try {
        suite = (Suite)xStream.fromXML(suiteFile);
      } catch (XStreamException e) {
        throw new ParserConfigurationException("Error when parse configuration file \"" + path + "\".");
      }
    } else {
      throw new FileNotFoundException("File \"" + path +"\" not found." );
    }
    return suite;
  }
}
